﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SYS.Common;
using SYS.Web.Models;
using FluentData;
namespace SYS.Web.Function
{
    public static class ModelExtension
    {
        /// <summary>
        /// 获取商品图片名称
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static string GetImgName(this TBItem item){
            var url = "";
            var l = item.imgurl.Split('/');
            if (l.Length > 0)
            {
                url = l[l.Length - 1];
            }
            return url;
        }
        /// <summary>
        /// 根据关键字kid生成网址
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public static string GetKeyPageUrl(this tbk_KeywordBySeed keyword) {
            return keyword.GetKeyPageUrl(siteConfig.CurrentSite,"/");
        }

        public static string GetKeyPageUrl(this tbk_KeywordBySeed keyword,Site site,string baseUrl)
        {
            return baseUrl +site.UrlPrefix+ keyword.Kid.ToString().IntToChar(site.CharArray) + site.UrlExtension;
        }

        public static int GetKidFromPageUrl(this tbk_KeywordBySeed keyword,Site site,string pageStr) {
            int kid = 0;
            string prefix = site.UrlPrefix;
            pageStr = pageStr.Remove(0, prefix.Length);
            int.TryParse(pageStr.CharToInt(site.CharArray), out kid);
            return kid;
        }

        public static string GetKeyDetailUrl(this TBItem item)
        {
            return "/g/" + item.ItemId;
        }
        /// <summary>
        /// 获取网站首页关键字kid集合
        /// 例如:1,343,86555,69595
        /// </summary>
        /// <param name="currentSite"></param>
        /// <returns></returns>
        public static List<tbk_KeywordBySeed> GetHomePageKids(this Site currentSite)
        {
            DateTime now=DateTime.Now;
            List<tbk_KeywordBySeed> keys = new List<tbk_KeywordBySeed>();
            string kids = "";
            IDbContext dbContext = new DbContext().ConnectionString(currentSite.DBConString, currentSite.DbProvider);
            SiteConfig dbSiteConfig = dbContext.Sql("select * from SiteConfig where SiteUrl=@0",currentSite.SiteUrl).QuerySingle<SiteConfig>();
            if (dbSiteConfig == null)
            {
                dbSiteConfig = new SiteConfig();
                dbSiteConfig.GroupName = "0";
                int maxKid = dbContext.Sql("select max(kid) from tbk_KeywordBySeed").QuerySingle<int>();
                kids = GetRandomKids(maxKid, 600);
                keys = dbContext.Sql("SELECT TOP 300 kid,Keyword FROM dbo.tbk_KeywordBySeed where kid in ("+kids+")").QueryMany<tbk_KeywordBySeed>();

                for (int i = 0; i < keys.Count; i++)
                {
                    kids += (i == 0 ? "" : ",") + keys[i].Kid;
                }
                dbSiteConfig.HomePageKids = kids;
                dbSiteConfig.KidsLastModify = now;
                dbSiteConfig.SiteUrl = currentSite.SiteUrl;
                dbContext.Insert<SiteConfig>("SiteConfig", dbSiteConfig).AutoMap().Execute();
            }
            else
            {
                kids = dbSiteConfig.HomePageKids;
                if (string.IsNullOrWhiteSpace(kids))
                {
                    int maxKid = dbContext.Sql("select max(kid) from tbk_KeywordBySeed").QuerySingle<int>();
                    kids = GetRandomKids(maxKid, 600);
                    keys = dbContext.Sql("SELECT TOP 300 kid,Keyword FROM dbo.tbk_KeywordBySeedwhere kid in (" + kids + ")").QueryMany<tbk_KeywordBySeed>();
                    for (int i = 0; i < keys.Count; i++)
                    {
                        kids += (i == 0 ? "" : ",") + keys[i].Kid;
                    }
                    dbContext.Sql("update SiteConfig set HomePageKids=@0 where SiteUrl=@1", kids, currentSite.SiteUrl).Execute();
                }
                else
                {
                    keys = dbContext.Sql("select kid,keyword from tbk_KeywordBySeed where kid in ("+kids+")").QueryMany<tbk_KeywordBySeed>();
                }
            }
            return keys;
        }

        /// <summary>
        /// 获取从搜索引擎获取来的长尾关键字
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public static string[] GetSuggestData(this tbk_KeywordBySeed keyword) { 
            string sData=keyword.S_Soso+","+keyword.S_Sogou+","+keyword.S_Baidu+","+keyword.S_360So+","+keyword.S_Bing;
            return sData.Split(new char[1] {','},StringSplitOptions.RemoveEmptyEntries);
        }
        /// <summary>
        /// 获取两组随机数据
        /// 一组站内互联,一组站群组互联
        /// </summary>
        /// <param name="keyword"></param>
        public static void GetRelateData(this Page page) {
            DateTime now = DateTime.Now;
            string kids = "";
            var currentSite = page.site;
            IDbContext dbContext = new DbContext().ConnectionString(currentSite.DBConString, currentSite.DbProvider);
            Kid_SiteKids ksite = dbContext.Sql("select * from Kid_SiteKids where kid=@0 and siteid=@1",page.keyword.Kid,currentSite.SiteId).QuerySingle<Kid_SiteKids>();
            List<tbk_KeywordBySeed> keys = new List<tbk_KeywordBySeed>();
            if (ksite == null)
            {
                ksite = new Kid_SiteKids();
                int maxKid = dbContext.Sql("select max(kid) from tbk_KeywordBySeed").QuerySingle<int>();
                while (keys.Count < 40)
                {
                    kids = GetRandomKids(maxKid, 100);
                    keys = dbContext.Sql("select top 40 kid,keyword from tbk_KeywordBySeed where kid in (" + kids + ")").QueryMany<tbk_KeywordBySeed>();
                }
                page.relateData = keys.Take(20).ToList();
                page.SitesData = keys.Skip(20).Take(20).ToList();
                ksite.Kid = page.keyword.Kid;
                ksite.SiteId = currentSite.SiteId;
                ksite.RelateKids = string.Join(",", page.relateData.Select(d => d.Kid).ToArray());
                ksite.SiteKids = string.Join(",", page.SitesData.Select(d => d.Kid).ToArray());
                ksite.LastModify = now;
                dbContext.Insert<Kid_SiteKids>("Kid_SiteKids", ksite).AutoMap().Execute();
            }
            else {
                page.relateData = dbContext.Sql("select * from tbk_KeywordBySeed where kid in ("+ksite.RelateKids+")").QueryMany<tbk_KeywordBySeed>();
                page.SitesData = dbContext.Sql("select * from tbk_KeywordBySeed where kid in (" + ksite.SiteKids + ")").QueryMany<tbk_KeywordBySeed>();
            }
        }
        /// <summary>
        /// 返回随机id组
        /// </summary>
        /// <param name="maxKid"></param>
        /// <param name="Amount"></param>
        /// <returns></returns>
        private static string GetRandomKids(int maxKid,int Amount) {
            Random rnd = new Random();
            string kids = "";
            for (int i = 0; i < 800; i++)
            {
                kids += rnd.Next(1, maxKid + 1) + ",";
            }
            kids += "0";
            return kids;
        }
    }
}